package com.user.service.user.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog.security.exception.ServiceException;
import com.blog.security.service.TokenService;
import com.comon.core.domain.result.R;
import com.comon.core.enums.ResultCode;
import com.comon.core.utils.BCryptUtils;
import com.user.domain.User.DTO.UserDTO;
import com.user.domain.User.DTO.UserRegDTO;
import com.user.domain.User.UserInfo;
import com.user.mapper.UserLayoutMapper;
import com.user.mapper.user.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-08-24
 * Time:15:26
 * Text：
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserLayoutMapper userLayoutMapper;
    @Autowired
    TokenService tokenService;
//    @Autowired
//    CircleCreateMapper circleCreateMapper;


    private static final String PHONE_REGEX = "^\\+?[0-9]{1,4}?[-.\\s]?([0-9]{1,4}[-.\\s]?){1,5}$";
    private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);

    @Value("${jwt.secret}")
    private String secret;

    public R<?> login(UserDTO userDTO, HttpServletRequest request){
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        UserInfo user = userMapper.selectOne(queryWrapper.select(UserInfo::getPassword,UserInfo::getUserName,UserInfo::getUserId,UserInfo::getPhone).eq(UserInfo::getPhone,userDTO.getPhone()));
        if(user == null){
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        } else if (BCryptUtils.matchesPassword(userDTO.getPassword(), user.getPassword())) {
            request.getSession().setAttribute("UserId",user.getUserId());
            return R.ok("登陆成功",tokenService.createToken(user.getUserId(),user.getPhone(),secret,user.getUserName(),-1));
        }
        return R.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public R<?> reg( UserRegDTO userRegDTO) {
        Map<String,String> map = new HashMap<>();
        if(!PHONE_PATTERN.matcher(userRegDTO.getPhone()).matches()){
            log.error("账号：{{ "+userRegDTO.getPhone()+" }}=>尝试注册，非法请求");
            throw new ServiceException(ResultCode.FAILED);
        }
        List<UserInfo> userList = userMapper.selectList(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getPhone,userRegDTO.getPhone()));
        if(CollectionUtil.isNotEmpty(userList)){
            log.error("账号：{{ "+userRegDTO.getPhone()+" }}=>尝试注册，账号已存在，请求失败");
            return R.fail(ResultCode.AILED_USER_EXISTS);
        }
        if(userRegDTO.getPassword().length() < 5){
            map.put("password","密码太短");
            log.error("账号：{{ "+userRegDTO.getPhone()+" }}=>尝试注册，密码太短，请求失败");
            return R.fail(3002,"不安全");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(userRegDTO.getPhone());
        userInfo.setPassword(BCryptUtils.encryptPassword(userRegDTO.getPassword()));
        System.out.println("添加账号");
        if(userMapper.insert(userInfo) == 1){
            log.info(" {{"+userRegDTO.getPhone()+"}} 账号注册成功！");
            return R.ok("注册成功");
        }
        return R.fail(ResultCode.FAILED);
    }

    @Override
    public R<?> layoutinfo(String token) {
        tokenService.delLoginUser(token);
        return R.ok();
    }

//    @Override
//    public R<?> layoutinfo(String token) {
//        Claims claims;
//        claims = JwtUtils.parseToken(token, secret);
//        String phone = JwtUtils.getUserPhone(claims);
//        UserInfo userInfo = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone,phone));
//        UserInfoGrade userInfoGrade = userLayoutMapper.selectOne(new LambdaQueryWrapper<UserInfoGrade>().eq(UserInfoGrade::getUId,userInfo.getUserId()));
//        String[] circles = userInfoGrade.getCircles().split("￥￥");
//        Map<String,String> circleInfo = new HashMap<>();
//        LambdaQueryWrapper<CircleCreate> queryWrapper = new LambdaQueryWrapper<>();
//        for(String str:circles){
//            String circleId = String.valueOf(circleCreateMapper.selectOne(queryWrapper.select(CircleCreate::getCirId).eq(CircleCreate::getCircle,str)));
//            circleInfo.put(str,circleId);
//        }
//        WebLayoutInfo webLayoutInfo = new WebLayoutInfo();
//        webLayoutInfo.setPhoto(userInfo.getPhoto());
//        webLayoutInfo.setName(userInfo.getUserName());
//        webLayoutInfo.setGrade(userInfoGrade.getGrade());
//        webLayoutInfo.setCircles(circleInfo);
//        return R.ok(webLayoutInfo);
//    }
    @Override
    public String getName(Long id){
        return userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().select(UserInfo::getUserName).eq(UserInfo::getUserId,id)).getUserName();
    }

    @Override
    public R<?> getUPhone(int uphone) {
         UserInfo userInfo = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone,uphone));
        if(userInfo != null){
            return R.ok(userInfo);
        }
        return R.fail("非法询问");
    }

    @Override
    public String getPhotoInfo(Long id) {
        String name =  userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().select(UserInfo::getPhoto).eq(UserInfo::getUserId,id)).getPhoto();
        return name;
    }


}

